import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';

var template = require("./templates/FileRequirementView.mustache");

const FileRequirementView = Mn.View.extend({
    tagName: 'tr',
    template: template,
    ui: {
        add_button: '.btn-add',
        view_button: ".btn-view",
        edit_button: ".btn-edit",
        valid_button: ".btn-validate",
        clickable_td: "td.clickable",
    },
    events: {
        "click @ui.add_button": "onAdd",
        "click @ui.edit_button": "onEdit",
        "click @ui.view_button": "onView",
        "click @ui.clickable_td": "onView",
        "click @ui.valid_button": "onValidate",
    },
    initialize() {
        this.config_channel = Radio.channel('config');
        this.section = this.config_channel.request(
            'get:form_section', 'files'
        );
    },
    hasPreview() {
        if (this.model.hasFile()) {
            return this.config_channel.request(
                'is:previewable', this.model.get('file_object')
            );
        } else {
            return false;
        }
    },
    templateContext() {
        return {
            has_preview: this.hasPreview(),
            has_edit: this.model.hasFile(),
            has_add: this.model.missingFile(),
            has_valid_link: this.model.hasFile() && this.model.get('validation') && this.section.can_validate && this.model.get('validation_status') != "valid",
            label: this.model.label(),
            show_status: true
        };
    },
    onFilePopupCallback(options) {
        this.triggerMethod('file:updated')
    },
    getCurrentUrl() {
        return window.location.href.replace('#', '').split('?')[0];
    },
    onAdd() {
        window.openPopup(
            this.getCurrentUrl() + "/addfile?file_type_id=" + this.model.get('file_type_id'),
            this.onFilePopupCallback.bind(this)
        );
    },
    onEdit() {
        window.openPopup(
            "/files/" + this.model.get("file_id"), this.onFilePopupCallback.bind(this)
        );
    },
    onView() {
        Radio.channel('facade').trigger(
            'show:preview',
            this.model.get('file_object'),
            this.model.label(),
        );
    },
    onValidate() {
        let res = this.model.validate();
        if (res) {
            this.model.setValid().then(() => this.render());
        }
    }
});
const FileOptionnalView = FileRequirementView.extend({
    templateContext() {
        let result = FileRequirementView.prototype.templateContext.call(this);
        result['show_status'] = false;
        return result;
    }
});
export {
    FileRequirementView,
    FileOptionnalView
};